package com.zbu.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;

import cn.hutool.json.JSONUtil;
import com.zbu.api.RemoteJudgeService;
import com.zbu.api.domain.UserExeResult;
import com.zbu.api.domain.dto.JudgeSubmitDTO;
import com.zbu.api.domain.vo.UserQuestionResultVO;
import com.zbu.common.core.constants.Constants;
import com.zbu.common.core.domain.R;
import com.zbu.common.core.enums.ProgramType;
import com.zbu.common.core.enums.QuestionResType;
import com.zbu.common.core.enums.ResultCode;
import com.zbu.common.core.utils.ThreadLocalUtil;
import com.zbu.common.security.exception.ServiceException;
import com.zbu.friend.domain.question.Question;
import com.zbu.friend.domain.question.QuestionCase;
import com.zbu.friend.domain.question.es.QuestionES;
import com.zbu.friend.domain.user.UserSubmit;
import com.zbu.friend.domain.user.dto.UserSubmitDTO;
import com.zbu.friend.elasticsearch.QuestionRepository;
import com.zbu.friend.mapper.question.QuestionMapper;
import com.zbu.friend.mapper.user.UserSubmitMapper;
import com.zbu.friend.rabbit.JudgeProducer;
import com.zbu.friend.service.user.IUserQuestionService;
import jakarta.json.Json;
import org.jacoco.agent.rt.internal_b6258fc.core.runtime.IRemoteCommandVisitor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserQuestionServiceimpl implements IUserQuestionService {
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private RemoteJudgeService remoteJudgeService;
    @Autowired
    JudgeProducer judgeProducer;
    @Autowired
    private UserSubmitMapper userSubmitMapper;
    @Override
    public R<UserQuestionResultVO> submit(UserSubmitDTO submitDTO) {
        Integer program=submitDTO.getProgramType();
        if(ProgramType.JAVA.equals(program)){
            //按照java标准
            JudgeSubmitDTO judgeSubmitDTO=assmbleJudgeSubmitDTO(submitDTO);
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw  new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        UserSubmit userSubmit= userSubmitMapper.selectCurrentUserSubmit(userId, examId, questionId, currentTime);
        UserQuestionResultVO resultVO=new UserQuestionResultVO();
        if(userSubmit==null){
            resultVO.setPass(QuestionResType.IN_JUDGE.getValue());
        }else{
            resultVO.setPass(userSubmit.getPass());
            resultVO.setExeMessage(userSubmit.getExeMessage());
            if(StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())){
                resultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return resultVO;
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO submitDTO) {
        Integer program=submitDTO.getProgramType();
        if(ProgramType.JAVA.equals(program)){
            //按照java标准
            JudgeSubmitDTO judgeSubmitDTO=assmbleJudgeSubmitDTO(submitDTO);
            judgeProducer.produceMsg(judgeSubmitDTO);
        }
        throw  new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    private JudgeSubmitDTO assmbleJudgeSubmitDTO(UserSubmitDTO submitDTO) {
        Long questionId=submitDTO.getQuestionId();
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        JudgeSubmitDTO judgeSubmitDTO=new JudgeSubmitDTO();
        if(questionES!=null){
            BeanUtil.copyProperties(questionES,judgeSubmitDTO);
        }else {
            Question question=questionMapper.selectById(questionId);
            BeanUtil.copyProperties(question,judgeSubmitDTO);
            questionES=new QuestionES();
            BeanUtil.copyProperties(question,questionES);
            questionRepository.save(questionES);
        }
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constants.USER_ID,Long.class));
        judgeSubmitDTO.setExamId(submitDTO.getExamId());
        judgeSubmitDTO.setProgramType(submitDTO.getProgramType());
        judgeSubmitDTO.setUserCode(codeConnect(submitDTO.getUserCode(),questionES.getMainFuc()));
        List<QuestionCase> questionCasesList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String> outputList = questionCasesList.stream().map(QuestionCase::getInput).collect(Collectors.toList());
        judgeSubmitDTO.setOutputList(outputList);
        return judgeSubmitDTO;
    }
    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }
}
